package org.ghost.consul.client.controller;

import org.ghost.consul.client.service.HomeService;
import org.ghost.consul.common.response.HttpRspDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created by yarnliu on 2017-10-25.
 */
@RequestMapping(value = "home")
@RestController
public class HomeController {
    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private Environment environment;

    @Autowired
    private HomeService homeService;


    @RequestMapping(value = "/rest", method = RequestMethod.GET)
    public HttpRspDTO rest() {
        return homeService.hello();
    }

    @RequestMapping(value = "/env", method = RequestMethod.GET)
    public HttpRspDTO env(@RequestParam(value = "prop") String prop) {
        String result = environment.getProperty(prop, "Not Found");
        return new HttpRspDTO(true, result);
    }

    /**
     * 从所有服务中选择一个服务
     */
    @RequestMapping(value = "/choose", method = RequestMethod.GET)
    public HttpRspDTO discover() {
        try {
            ServiceInstance result = loadBalancerClient.choose("helloService");
            return new HttpRspDTO(true, result);
        } catch (Exception e) {
            logger.error("*****discover出现错误:" + e.getMessage(), e);
            return new HttpRspDTO(false, "E400000", e.getMessage());
        }
    }

    /**
     * 获取所有服务
     */
    @RequestMapping(value = "/instances", method = RequestMethod.GET)
    public HttpRspDTO services() {
        try {
            List<ServiceInstance> result = discoveryClient.getInstances("helloService");
            return new HttpRspDTO(true, result);
        } catch (Exception e) {
            logger.error("*****services出现错误:" + e.getMessage(), e);
            return new HttpRspDTO(false, "E400000", e.getMessage());
        }
    }
}
